package org.ouniao.jprint.client;

import java.io.File;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

@Component
public class ReceiveFile {

	@Value("${file_folder}")
	private String fileFolder;

	@JmsListener(destination = "uploadfile_listenner", containerFactory = "jmsListenerContainerQueue")
	public void printFile(Object[] obj) {
		try {
			String fileName = (String) obj[0];
			byte[] fileBytes = (byte[]) obj[1];
			String filePath = fileFolder.concat(fileName);
			FileCopyUtils.copy(fileBytes, new File(filePath));
			ComThread.InitSTA();
			ActiveXComponent word = new ActiveXComponent("Word.Application");
			Dispatch doc = null;
			Dispatch.put(word, "Visible", new Variant(false));
			Dispatch docs = word.getProperty("Documents").toDispatch();
			doc = Dispatch.call(docs, "Open", filePath).toDispatch();
			try {
				Dispatch.call(doc, "PrintOut");
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (doc != null) {
						Dispatch.call(doc, "Close", new Variant(0));
					}
				} catch (Exception e2) {
					e2.printStackTrace();
				}
				ComThread.Release();
			}

		} catch (IOException e1) {
			e1.printStackTrace();
		}

	}

}
